var app = getApp();

function checktaken(that) {
  if (app.accesstoken == "") {
    setTimeout(function() {
      checktaken(that);
    }, 500);
  } else {
    app.businfo = "";
    that.getbusinfo("");
  }
}
//线路查询
Page({

  /**
   * 页面的初始数据
   */
  data: {
    buslinesinfo: "",
    update: 0,
    network: false,
    appColor: app.appColor,
    // news: [
    //   '城际公交一个人一天凭身份证只能在网上购买一次。',
    //   '寒流来袭，你的秋裤准备好了吗？',
    //   '快收下，新鲜出炉冬季实用穿搭指南~'
    // ],
    // text: [
    //   '城际公交一个人一天凭身份证只能在网上购买一次。',
    //   '寒流来袭，你的秋裤准备好了吗？',
    //   '快收下，新鲜出炉冬季实用穿搭指南~'
    // ],
    // autoplay: true,
    // // interval: 3000,
    // duration: 500,
    // isTarget: "",
    // // 文字滚动跑马灯
    // text: "这是一条会滚动的文字滚来滚去的文字跑马灯，不错哟",
    // marqueePace: 1, //滚动速度
    // marqueeDistance: 0, //初始滚动距离
    // marquee_margin: 30,
    // size: 14,
    // interval: 20 // 时间间隔
    text: '',
    marqueePace: 1, //滚动速度
    marqueeDistance: 0, //初始滚动距离
    marqueeDistance2: 0,
    marquee2copy_status: false,
    marquee2_margin: 60,
    size: 16,
    orientation: 'left', //滚动方向
    interval: 20 // 时间间隔
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    // 极个别情况出现空白页，原因是未获取到Token！
    let that = this;
    // 防止app.js中networking请求失败

    // wx.request({
    //   url: `https://img.hn96606.com/images/notice.json?${app.startdate}`,
    //   header: {
    //     'content-type': 'application/json'
    //   },
    //   //请求后台数据成功
    //   success: function (res) {
    //     console.log(res)
    //     that.setData({
    //       news: res.notice
    //     })
    //   }  
    // })

    try {
      if (app.networkData.length == 0) {
        app.networking();
      }
      if (options.globalcode != null) {
        app.globalcode = options.globalcode;
        wx.setStorage({
          key: 'globalcode',
          data: options.globalcode
        });
        app.target = options.target;
        if (options.date) {
          app.startdate = options.date;
        }
      }
      this.load(app.startdate);
      this.currentdate = app.startdate;
    } catch (err) {}

  },
  // ====================================
  notice: function(e) {
    let textData = `1、${this.data.news[0]}\n2、${this.data.news[1]}\n3、${this.data.news[2]}`
    wx.showModal({
      title: '提示',
      showCancel: false,
      confirmText: '我知道啦',
      content: textData,
      success(res) {
        if (res.confirm) {} else if (res.cancel) {}
      }
    })
  },

  // 用户信息授权按钮  
  bindGetUserInfo(e) {
    try {
      let that = this;
      app.showLoadings();
      this.setData({
        shouquanModal: false,
      })
      var user = e.detail;
      app.userinfo.nickname = user.userInfo.nickName ? user.userInfo.nickName : '';
      app.userinfo.headimg = user.userInfo.avatarUrl;
      that.putUserData(this.codes, user.iv, user.encryptedData);
    } catch (err) {}
  },



  // =========================================

  // 车票信息
  load: function(dates) {
    if (app.accesstoken == "") {
      checktaken(this);
    } else {
      app.businfo = "";
      this.getbusinfo("");
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    app.showLoadings();
    let isDate = app.startdate;
    if (isDate == null) {
      this.setData({
        date: app.dates()
      })
    } else {
      this.setData({
        date: isDate
      });
    }

    this.getbusinfo(app.startdate);
    // // 文字滚动跑马灯
    // // 页面显示

    // var that = this;

    // var length = that.data.text.length * that.data.size; //文字长度

    // var windowWidth = wx.getSystemInfoSync().windowWidth; // 屏幕宽度
    // //console.log(length,windowWidth);
    // that.setData({
    //   length: length,
    //   windowWidth: windowWidth
    // });
    // that.scrolltxt(); // 第一个字消失后立即从右边出现

    // 文字滚动跑马灯2
    try {
      var vm = this;
      var length = app.networkData.Notice.length * vm.data.size; //文字长度
      var windowWidth = wx.getSystemInfoSync().windowWidth; // 屏幕宽度
      vm.setData({
        text: app.networkData.Notice
      })
      vm.setData({
        length: length,
        windowWidth: windowWidth,
        marquee2_margin: length < windowWidth ? windowWidth - length : vm.data.marquee2_margin //当文字长度小于屏幕长度时，需要增加补白
      });
      if (length < windowWidth) {
        return
      }
      var timeoutId = setTimeout(() => {
        vm.run1();
      }, 2200)
    } catch (err) {

    }
  },

  run1: function() {
    var vm = this;
    try{
      var interval = setInterval(function() {
        if (-vm.data.marqueeDistance2 < vm.data.length) {
          // 如果文字滚动到出现marquee2_margin=30px的白边，就接着显示
          vm.setData({
            marqueeDistance2: vm.data.marqueeDistance2 - vm.data.marqueePace,
            marquee2copy_status: vm.data.length + vm.data.marqueeDistance2 <= vm.data.windowWidth + vm.data.marquee2_margin,
          });
        } else {
          if (-vm.data.marqueeDistance2 >= vm.data.marquee2_margin) { // 当第二条文字滚动到最左边时
            vm.setData({
              marqueeDistance2: vm.data.marquee2_margin // 直接重新滚动
            });
            clearInterval(interval);
            vm.run1();
          } else {
            clearInterval(interval);
            vm.setData({
              marqueeDistance2: -vm.data.windowWidth
            });
            vm.run1();
          }
        }
      }, vm.data.interval);
    }catch(err){}
  },
  scrolltxt: function() {
    var that = this;
    var length = that.data.length; //滚动文字的宽度
    var windowWidth = that.data.windowWidth; //屏幕宽度
    if (length > windowWidth) {
      var interval = setInterval(function() {
        var maxscrollwidth = length + that.data.marquee_margin; //滚动的最大宽度，文字宽度+间距
        //如果需要一行文字滚完后再显示第二行可以修改marquee_margin值等于windowWidth即可
        var crentleft = that.data.marqueeDistance;
        if (crentleft < maxscrollwidth) { //判断是否滚动到最大宽度
          that.setData({
            marqueeDistance: crentleft + that.data.marqueePace
          })
        } else {
          //console.log("替换");
          that.setData({
            marqueeDistance: 0 // 直接重新滚动
          });
          clearInterval(interval);
          that.scrolltxt();
        }
      }, that.data.interval);
    } else {
      that.setData({
        marquee_margin: "1000"
      }); //只显示一条不滚动右边间距加大，防止重复显示
    }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function(res) {
    if (res.from === 'menu') {}
    return {
      title: app.stationName + '-' + app.target,
      path: '/pages/buslines/buslines?globalcode=' + app.globalcode + "&target=" + app.target + "&date=" + this.currentdate + "&user=" + app.accesstoken,
      success: function(res) {},
      fail: function(xhr) {
        // 转发失败
      }
    }
  },
  // 手机放在这个页面绑定！！！！！！！！！！！！！！！！！！！！！！
  selectbusline: function(e) {
    let getToken = app.accesstoken ? app.accesstoken : app.stanToken;
    var businfo = e.currentTarget.dataset.buslineinfo;
    if (!businfo.IsAllow) {
      wx.showModal({
        content: '该班次目前网上停售，详情请咨询车站',
        showCancel: false,
        success: function(res) {
          if (res.confirm) {}
        }
      })
      // 若是停售班次,则在此处终止程序的执行
      return
    }

    // 判断用户是否绑定手机号(手机号用于给用户发送短信)
    if (app.IsRegister == true) {
      // 存储用户选择的班次信息，orderpre页面进行数据渲染
      try {
        businfo.isbao = this.data.isbao;
        businfo.Price = businfo.disPrice;
        wx.setStorage({
          key: "busLineData",
          data: businfo
        })
        wx.navigateTo({
          url: '/pages/orderpre/orderpre'
        });
      } catch (err) {}
    } else {
      // 如果没有获取到Token则返回到首页，重新获取
      if (!getToken) {
        wx.navigateBack({});
      }
      app.businfo = e.currentTarget.dataset.buslineinfo;

      wx.showModal({
        content: '请绑定手机号后再来购票哦！',
        showCancel: false,
        success: function(res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/bindPhone/bindPhone',
            });
          }
        }
      });
    };
  },
  selectDate: function() {
    wx.navigateTo({
      url: '/pages/calendar/calendar'
    });
  },

  beforeday: function(e) {
    try {
      var date = e.currentTarget.dataset.day;
      if (date == "null") {
        this.setData({
          color: true
        })
        this.currentdate = date;
        return;
      }
      app.startdate = date;
      app.showLoadings();
      this.getbusinfo(date);
    } catch (err) {}

  },

  afterday: function(e) {
    try {
      var date = e.currentTarget.dataset.day;
      if (date == "null") {
        this.setData({
          color: true
        })
        return;
      }
      app.startdate = date;
      this.currentdate = date;
      app.showLoadings();
      this.getbusinfo(date);
    } catch (err) {}
  },

  getbusinfo: function(startdate) {
    this.data.isTarget = app.target;
    let getToken = app.accesstoken ? app.accesstoken : app.stanToken;
    try {
      if (startdate == "") {
        startdate = app.startdate;
      };
      var that = this;
      wx.request({
        url: app.serviceurl + 'StationLine/QueryBus',
        header: {
          Authorization: "Bearer " + getToken
        },
        data: {
          StartStaionId: app.globalcode,
          EndCityName: this.data.isTarget,
          QueryBusLineDate: startdate == "" ? app.startdate : startdate
        },
        dataType: 'json',
        success: function(res) {
          if(res.data.IsCanRefund){
            app.isRefund = res.data.IsCanRefund;
          }
          if (res.data.Exdate == 'null') {
            that.setData({
              colors: '#dedede',
              leftOff: true
            })
          } else {
            that.setData({
              colors: 'white',
              leftOff: false
            })
          };

          if (res.data.Nextdate == 'null') {
            that.setData({
              offColors: '#dedede',
              rightOff: true
            })
          } else {
            that.setData({
              offColors: 'white',
              rightOff: false
            })
          };
          var str = "星期" + "日一二三四五六".charAt(new Date(startdate).getDay());
          that.setData({
            buslinesinfo: res.data.BusLineList,
            result: res.data,
            date: startdate,
            exday: res.data.Exdate,
            afday: res.data.Nextdate,
            request: res.errMsg,
            isbao: res.data.IsCanInsure,
            seek: str,
            network: false
          });
        },
        fail: function() {
          try {
            that.setData({
              network: true
            })
          } catch (e) {}
        },
        complete: function(res) {
          app.hideLoadings();
        }
      })
    } catch (err) {}

  }
})